package com.miaostars.apakey.checks;

import com.miaostars.apakey.Apakey;
import com.miaostars.apakey.utils.PlayerData;
import org.bukkit.entity.Player;

import java.util.List;

public class AutoClickChecks {
    
    private final Apakey plugin;
    
    public AutoClickChecks(Apakey plugin) {
        this.plugin = plugin;
    }
    
    public boolean checkAutoClick(Player player, PlayerData data) {
        if (!plugin.getConfigManager().getConfig().getBoolean("checks.autoclick.enabled")) {
            return false;
        }
        
        if (player.hasPermission("apakey.bypass")) {
            return false;
        }
        
        List<Long> clicks = data.getClicks();
        long currentTime = System.currentTimeMillis();
        
        // Remove clicks older than 1 second
        clicks.removeIf(clickTime -> currentTime - clickTime > 1000);
        
        // Check for consistent click patterns (indication of autoclicker)
        if (clicks.size() >= 10) { // Minimum clicks to analyze
            double averageInterval = calculateAverageInterval(clicks);
            double deviation = calculateDeviation(clicks, averageInterval);
            
            // If deviation is too low, it's likely an autoclicker
            if (deviation < 20) { // 20ms deviation threshold
                data.incrementAutoClickViolations();
                
                if (data.getAutoClickViolations() > plugin.getConfigManager().getConfig().getInt("checks.autocclick.max-violations")) {
                    return true;
                }
            } else {
                data.decrementAutoClickViolations();
            }
        }
        
        return false;
    }
    
    private double calculateAverageInterval(List<Long> clicks) {
        if (clicks.size() < 2) return 0;
        
        long total = 0;
        for (int i = 1; i < clicks.size(); i++) {
            total += clicks.get(i) - clicks.get(i-1);
        }
        
        return (double) total / (clicks.size() - 1);
    }
    
    private double calculateDeviation(List<Long> clicks, double average) {
        if (clicks.size() < 2) return 0;
        
        double sum = 0;
        for (int i = 1; i < clicks.size(); i++) {
            double diff = clicks.get(i) - clicks.get(i-1) - average;
            sum += diff * diff;
        }
        
        return Math.sqrt(sum / (clicks.size() - 1));
    }
}
